package com.hequ.merchant.banner.api;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import java.util.Map;

import static com.hequ.merchant.banner.util.AppConstant.BASE_USL;

/**
 * Created by 柯尊诚 on 2015/10/27.
 * kzc
 */
public abstract class BannerRequest<T> extends StringRequest {

    private OnRequestListener<T> listener;

    public BannerRequest(int method, String url,OnRequestListener<T> listener) {
        super(method, BASE_USL + url, null, null);
        this.listener = listener;
    }

    public BannerRequest(String url,OnRequestListener<T> listener) {
        super(BASE_USL + url, null, null);
        this.listener = listener;
    }

    public void setListener(OnRequestListener<T> listener) {
        this.listener = listener;
    }

    @Override
    protected void deliverResponse(String response) {
        listener.onSuccess(parseResponse(response));
    }

    public abstract T parseResponse(String result);

    @Override
    public void deliverError(VolleyError error) {
        listener.onFailed();
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> params = listener.getParams();

        params.put("token","hequ");
        Log.d("xxparams: ", params + "");
        return params;
    }


    @Override
    public String getUrl() {
        String url = super.getUrl();

        if (getMethod() == Method.GET || getMethod() == Method.PUT) {
            StringBuilder builder = new StringBuilder();

            try {
                Map<String, String> params = getParams();

                for (Map.Entry<String, String> entry : params.entrySet()) {
                    builder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }

                builder.append("os=android");

                url = url + (url.lastIndexOf("?") > 0 ? "&" : "?") + builder.toString();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Log.d("xxrequest: ", url);

        return url;
    }
}
